package com.auto.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auto.entity.Site;
import com.auto.entity.User;
import com.auto.rep.SiteRep;
import com.auto.rep.UserRep;

@Controller
public class UserController {
	@Autowired
	UserRep userRep;
	
	@Autowired
	SiteRep siteRep;

	@RequestMapping(value = "user", method = RequestMethod.GET)
	@ResponseBody
	public List<User> getUsers(@RequestParam("siteId") Long siteId) {
		return userRep.findBySiteId(siteId);
	}

	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	@ResponseBody
	public User getUser(@PathVariable("id") Long id) {
		return userRep.findOne(id);
	}

	
	
	@RequestMapping(value = "user/{id}", method = RequestMethod.POST)
	@ResponseBody
	public void updateUser(@PathVariable("id") Long id, User user) {
		user.setId(id);
		userRep.save(user);
	}

	@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public void deleteUser(@PathVariable("id") Long id) {
		userRep.delete(id);
	}

	@RequestMapping(value = "user", method = RequestMethod.POST)
	@ResponseBody
	public User addUser(User user, @RequestParam("siteId") Long siteId) {
		Site site = siteRep.findOne(siteId);
		user.setSite(site);
		return userRep.save(user);
	}
}
